/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Creditos;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author alrojas
 */
public class IAgregar extends JFrame{
    
    private JLabel      clienteLab;
    private JTextField  clienteCam;
    //private JButton     clienteBut;
    private JTextField  cliente2Cam;
    private JTable      listaTab;
    private DefaultTableModel modeloTab;
    private TableRowSorter<TableModel> clasificador;
    
    private JLabel interesesLab;
    private JLabel moraLab;
    private JLabel montoCompraLab;
    private JLabel nroCuotaslLab;
    private JLabel montoTotalLab;
    
    private JTextField montoTotalTex; 
    private JTextField interesesTex;
    private JTextField montoCompraTex;
    private JTextField moraTex;
    private JTextField nroCuotaslTex;
    
    private JButton guardarBut;
    private JButton generarBut;
    private JButton descartarBut;
    
    public IAgregar(JFrame padre){
        this.setLayout(new GridBagLayout());
        this.setTitle("Agregar Crédito");
        
        inicializarComponentes(padre);
        inicializarListeners(padre);
        
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public void inicializarComponentes(JFrame padre){
        
        final Ventas.IAgregar padreReal = (Ventas.IAgregar) padre;
        
        GridBagConstraints limites = new GridBagConstraints();
        limites.insets = new Insets(2, 2, 2, 2);
        
        limites.fill = GridBagConstraints.HORIZONTAL;
        
        JPanel panelCliente = new JPanel(new FlowLayout());
        clienteLab = new JLabel("Cliente: "); 
        clienteCam = new JTextField(10); clienteCam.setText(padreReal.getCodigoCliente()); clienteLab.setLabelFor(clienteCam); clienteCam.setHorizontalAlignment(JLabel.CENTER); clienteCam.setEditable(false);
        cliente2Cam = new JTextField(42); cliente2Cam.setText(padreReal.getNombreCliente()); clienteLab.setLabelFor(clienteCam); cliente2Cam.setHorizontalAlignment(JLabel.CENTER); cliente2Cam.setEditable(false);
        panelCliente.add(clienteLab); panelCliente.add(clienteCam); panelCliente.add(cliente2Cam); //panelCliente.add(clienteBut);
        limites.gridx = 0; limites.gridy = 0;
        add(panelCliente,limites);
        
        limites.fill = GridBagConstraints.CENTER;
        
        JPanel panelCredito = new JPanel(new GridLayout(2,4));
        interesesLab = new JLabel("Intéreses (%): "); interesesLab.setHorizontalAlignment(JLabel.RIGHT);
        moraLab = new JLabel("Mora (%): "); moraLab.setHorizontalAlignment(JLabel.RIGHT);
        montoCompraLab = new JLabel("M. Compra (S/.): "); montoCompraLab.setHorizontalAlignment(JLabel.RIGHT);
        nroCuotaslLab = new JLabel("Nro. Cuotas: "); nroCuotaslLab.setHorizontalAlignment(JLabel.RIGHT);
        interesesTex = new JTextField("1.00",12); interesesTex.setHorizontalAlignment(JTextField.RIGHT);
        montoCompraTex = new JTextField(padreReal.getMontoCompra(),12); /*montoCompraTex.setText(padreReal.getMontoCompra());*/ montoCompraTex.setHorizontalAlignment(JTextField.RIGHT); montoCompraTex.setEditable(false);
        moraTex = new JTextField("1.00",12); moraTex.setHorizontalAlignment(JTextField.RIGHT);//moraTex.setEditable(false);
        nroCuotaslTex = new JTextField("1",12); nroCuotaslTex.setHorizontalAlignment(JTextField.RIGHT);
        panelCredito.add(interesesLab); panelCredito.add(interesesTex); panelCredito.add(moraLab); panelCredito.add(moraTex);
        panelCredito.add(nroCuotaslLab);panelCredito.add(nroCuotaslTex); panelCredito.add(montoCompraLab);panelCredito.add(montoCompraTex);
        limites.gridy = 1;
        add(panelCredito,limites);
        
        DefaultTableCellRenderer rendererCentro = new DefaultTableCellRenderer();
        rendererCentro.setHorizontalAlignment(JLabel.CENTER);
        
        DefaultTableCellRenderer rendererDerecho = new DefaultTableCellRenderer();
        rendererDerecho.setHorizontalAlignment(JLabel.RIGHT);

        Vector<String> columnNames = new Vector<String>(); columnNames.add("Nro Cuota"); columnNames.add("Amortización"); columnNames.add("Intereses"); columnNames.add("Monto Cuota"); columnNames.add("F. Vencimiento");     
        Vector productos = new Vector();
        modeloTab = new DefaultTableModel(productos,columnNames){
            @Override
            public boolean isCellEditable (int row, int column)
            {
                return false;
            }  
        };
            
        this.clasificador = new TableRowSorter<TableModel>(modeloTab);
        listaTab = new JTable(modeloTab); listaTab.setRowHeight(20); listaTab.setRowSorter(clasificador); listaTab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ((DefaultTableCellRenderer)listaTab.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
        listaTab.getColumnModel().getColumn(0).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(1).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(2).setCellRenderer(rendererCentro);
        listaTab.getColumnModel().getColumn(3).setCellRenderer(rendererCentro);  
        listaTab.getColumnModel().getColumn(4).setCellRenderer(rendererCentro); 
        
        limites.gridy = 2; //limites.gridwidth = 4;
        JScrollPane barras = new JScrollPane(listaTab); barras.setPreferredSize(new Dimension(600, 150));
        add(barras,limites);
        
        //////
        limites.anchor = GridBagConstraints.EAST;
        
        JPanel panelMontoTotal = new JPanel(new FlowLayout());
        montoTotalLab = new JLabel("M. Total (S/.)");
        montoTotalTex = new JTextField("0.00",7); montoTotalTex.setHorizontalAlignment(JTextField.RIGHT);
        limites.gridy = 3; //limites.gridwidth = 3;
        panelMontoTotal.add(montoTotalLab); panelMontoTotal.add(montoTotalTex);
        add(panelMontoTotal,limites);
        
        limites.anchor = GridBagConstraints.CENTER;
        
        JPanel panelBotones = new JPanel(new FlowLayout());
        guardarBut = new JButton("Guardar", new ImageIcon("figuras/save32.png"));
        guardarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        guardarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        guardarBut.setVerticalAlignment(SwingConstants.CENTER);
        generarBut = new JButton("Generar Cuotas", new ImageIcon("figuras/instalment232.png"));
        generarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        generarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        generarBut.setVerticalAlignment(SwingConstants.CENTER);
        descartarBut = new JButton("Descartar", new ImageIcon("figuras/trash32.png"));
        descartarBut.setHorizontalTextPosition(SwingConstants.CENTER);
        descartarBut.setVerticalTextPosition(SwingConstants.BOTTOM) ;
        descartarBut.setVerticalAlignment(SwingConstants.CENTER);
        limites.gridy = 4; //limites.gridwidth = 3;
        panelBotones.add(guardarBut); panelBotones.add(generarBut); panelBotones.add(descartarBut);
        add(panelBotones,limites);
         
    }
    
    public void inicializarListeners(JFrame padre){
        
        final Ventas.IAgregar padreReal = (Ventas.IAgregar) padre;
        
        guardarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                
                padreReal.comprarBut.doClick();
                
                Credito credito = new Credito("", modeloTab);
                credito.setIntereses(Float.valueOf(interesesTex.getText()));
                credito.setNroCuotas(Integer.valueOf(nroCuotaslTex.getText()));
                credito.setMora(Float.valueOf(moraTex.getText()));
                if(listaTab.getRowCount() > 0){
                    try {
                        CCredito.agregar(credito);
                        setVisible(false);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(IAgregar.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SQLException ex) {
                        Logger.getLogger(IAgregar.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                else{
                    JOptionPane.showMessageDialog(null,"No hay monto que fraccionar!","Aviso",JOptionPane.WARNING_MESSAGE); 
                }
                

            }
        });
        
        generarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                double P = Float.valueOf(montoCompraTex.getText()); // Monto Parcial
                double i = Float.valueOf(interesesTex.getText()) / 100; // Intereses    
                double n = Float.valueOf(nroCuotaslTex.getText()); // Nro Cuotas
                
                double R =  P + (P * i) / n;
                generarCuotas(P,i,R,n); 
                
            }
        });
        
        descartarBut.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
    }
    
    public void generarCuotas(double montoParcial, double intereses, double montoCuota, double nroCuotas){
        
        DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
        simbolos.setDecimalSeparator('.');
        DecimalFormat df = new DecimalFormat("#0.00",simbolos);
        
        SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
        Calendar fechaHoy = Calendar.getInstance(); 
                    
        modeloTab.getDataVector().clear();
        
        for(int i = 0; i < (int)nroCuotas; i++){  
            
            /* Metodo Frances
            double amortizacion = montoCuota - montoParcial * intereses; 
            double interesesCuota = montoCuota - amortizacion;
            montoParcial -= amortizacion; */
            
            /* Metodo Simple */
            double amortizacion = montoParcial / nroCuotas;
            double interesesCuota =  montoParcial * intereses / nroCuotas;
            
            fechaHoy.add(Calendar.DATE,30);
            
 
            Vector < String > cuota = new Vector < String >();
            cuota.add(String.valueOf(i + 1));
            cuota.add(df.format(amortizacion));
            cuota.add(df.format(interesesCuota));  
            cuota.add(df.format(amortizacion + interesesCuota));
            cuota.add(String.valueOf(sdf.format(fechaHoy.getTime())));  
            modeloTab.addRow(cuota);
        }
        
        montoTotalTex.setText(df.format(montoParcial + (montoParcial * intereses)));

    }
 
}
